package com.ruoyi.yl.rocketmq.listern;

import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHeaders;

@RocketMQTransactionListener
@Slf4j
public class TransactionListenerImpl implements RocketMQLocalTransactionListener {

    @Override
    public RocketMQLocalTransactionState executeLocalTransaction(Message msg, Object arg) {
        // 执行本地事务
        try {
            // 业务逻辑...
            MessageHeaders headers = msg.getHeaders();
            String topic = (String)headers.get("rocketmq_TOPIC");
            Object payload = msg.getPayload();
            // 如果是JSON字符串
            if (payload instanceof String) {
                log.info("收到业务数据：{}", (String) payload);
            }

//            log.info("收到业务数据：{}", (String) payload);
            log.info("事物MQ监听器:mqs:{} arg:{}",msg,arg);
            return RocketMQLocalTransactionState.COMMIT;
        } catch (Exception e) {
            return RocketMQLocalTransactionState.ROLLBACK;
        }
    }

    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message msg) {
        // 检查本地事务状态
        return RocketMQLocalTransactionState.COMMIT;
    }
}